import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, getTokenTimeStamp, removeToken } from '@/utils/auth'
import router from '@/router'
//! 环境变量
// console.log(process.env)// {NODE_ENV: 'development', VUE_APP_BASE_API: '/dev-api', BASE_URL: '/'}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://127.0.0.1:5050/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // 请求超时时间
  timeout: 5000
})
// 设置超时时间
const TIMEOUT = 36000
function isCheckTimeOut() {
  const oldTime = getTokenTimeStamp()
  // console.log((Date.now() - oldTime) / 1000)
  return (Date.now() - oldTime) / 1000 > TIMEOUT
}
// !请求拦截器
service.interceptors.request.use(
  config => {
    // console.log(store.getters.token)
    // console.log(getToken())
    if (getToken()) {
      if (isCheckTimeOut()) {
        // 清空数据
        store.commit('user/RESET_STATE')
        // 清除token
        removeToken()
        // 跳转登录页
        router.push('/login')
        return Promise.reject(new Error('token过期,请重新登录'))
      }
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// !响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    //! 失败提示
    if (!res.success) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
    //! 成功提示
    Message({
      message: res.message || '成功',
      type: 'success',
      duration: 5 * 1000
    })
    // 返回响应数据
    return res
  },
  error => {
    // /console.log('err' + error) // for debug
    if (error.response.status === 401) {
      // 清空数据
      store.commit('user/RESET_STATE')
      // 清除token
      removeToken()
      // 跳转登录页
      router.push('/login')
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
